<template>
    <div class="song-audio">
        <audio :src='url' controls="controls" id="player" preload="true" @timeupdate="timeupdate"  @canplay="startPlay"  @ended="ended"></audio>
    </div>
</template>

<script>
    import { mapGetters } from 'vuex'

    export default {
        name: 'song-audio',
        computed: {
            ...mapGetters([
                'id', // 音乐id
                'url', // 音乐链接
                'isPlay', // 播放状态
            ])
        },
        watch: {
            // 监听播放还是暂停
            isPlay: function () {
                this.togglePlay()
            }
        },
        methods: {
            // 开始/暂停
            togglePlay () {
                let player = document.querySelector('#player')
                console.log(player+"SongAudio我的开始/暂停")
                if (this.isPlay) {
                    player.play()
                } else {
                    player.pause()
                }
            },
            // 获取歌曲链接后准备播放
            startPlay () {
                let player = document.querySelector('#player')

                this.$store.commit('setDuration', player.duration)
                window.sessionStorage.setItem('duration', JSON.stringify(player.duration))
                console.log(player+"我的开始/暂停")
                //  开始播放
                player.play()
            },
            // 音乐播放时记录音乐的播放位置
            timeupdate () {
                let player = document.querySelector('#player')
                this.$store.commit('setCurTime', player.currentTime)
                window.sessionStorage.setItem('curTime', JSON.stringify(player.currentTime))
            },
            // 音乐播放结束时触发
            ended () {
                this.isPlay = false
            }
        }
    }
</script>

<style>
    #player {
        color: red;
        display: none;
    }
</style>
